﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace tools.Tooling
{
    class ByteTool
    {
        /// <summary>
        /// byte[]转audioclip
        /// </summary>
        /// <param name="bs">byte[]</param>
        /// <param name="audioFrequency">采样频率</param>
        /// <param name="is3D">是否是3D音频播放</param>
        /// <returns></returns>
        public static AudioClip ConvertBytesToClip(byte[] bs, int audioFrequency, bool is3D)
        {
            float[] samples = new float[bs.Length / 2];
            float rescaleFactor = 32767;
            short st = 0;
            short ft = 0;
            for (int i = 0; i < bs.Length; i++)
            {
                st = BitConverter.ToInt16(bs, i);
                ft = (short)(st / rescaleFactor);
                samples[i / 2] = ft;
            }
            AudioClip cp = AudioClip.Create("clip", samples.Length, 1, audioFrequency, is3D);
            cp.SetData(samples, 0);
            return cp;
        }
        /// <summary>
        /// audioclip转byte[]
        /// </summary>
        /// <param name="clip">AudioClip</param>
        /// <returns></returns>
        public static byte[] ConvertClipToBytes(AudioClip clip)
        {
            float[] samples = new float[clip.samples];
            clip.GetData(samples, 0);
            short[] intData = new short[samples.Length];
            //converting in 2 float[] steps to Int16[], //then Int16[] to Byte[]
            byte[] bytesData = new byte[samples.Length * 2];
            //bytesData array is twice the size of
            //dataSource array because a float converted in Int16 is 2 bytes.
            int rescaleFactor = 32767; //to convert float to Int16
            for (int i = 0; i < samples.Length; i++)
            {
                intData[i] = (short)(samples[i] * rescaleFactor);
                byte[] byteArr = new byte[2];
                byteArr = BitConverter.GetBytes(intData[i]);
                byteArr.CopyTo(bytesData, i * 2);
            }
            return bytesData;
        }
        /// <summary>
        /// bytr[]转Texture2D
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <returns></returns>
        public static Texture2D ByteToTex2d(byte[] bytes, int w = 2048, int h = 1024)
        {
            Texture2D tex = new Texture2D(w, h);
            tex.LoadImage(bytes);
            return tex;
        }
    }
}
